<template>
  <div class="my-container mt-4">
    <div class="card class-list-card shadow border-0">
      <!-- 表头 -->
      <div
        class="card-header bg-primary"
        style="border-radius: 1.2rem 1.2rem 0 0;"
      >
        <h3
          class="mb-0 text-white fw-semibold text-start"
          style="font-size: 1.25rem;"
        >
          班级列表
        </h3>
      </div>
      <!-- 内容区 -->
      <ul class="list-group list-group-flush">
        <li
          v-for="cls in classes"
          :key="cls.classesId"
          class="list-group-item d-flex justify-content-between align-items-center"
          style="background: #fff; border-bottom: 1.5px solid #eef3fa;"
        >
          <div>
            <strong
              class="text-dark"
              style="font-size:1.11rem;"
            >{{ cls.classesName }}</strong>
            <div class="text-muted">
              教师：{{ teacherNamesMap[cls.classesId] || '加载中...' }}
            </div>
            <div class="text-muted">
              学生人数：{{ studentCountMap[cls.classesId] ?? '加载中...' }}
            </div>
            <div class="text-muted">
              所属课程：{{ cls.course?.courseName || courseNameMap[cls.classesId] || '加载中...' }}
            </div>
          </div>
          <button
            class="btn btn-primary btn-sm rounded-pill px-3"
            :disabled="hasJoined"
            @click="joinClass(cls.classesId)"
          >
            {{ hasJoined ? '不可加入' : '加入班级' }}
          </button>
        </li>
        <!-- 无班级时提示 -->
        <li
          v-if="classes.length === 0"
          class="list-group-item text-center text-muted py-4"
          style="background:#fff;"
        >
          暂无班级
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted } from 'vue'
  import axios from 'axios'
  import { useRoute } from 'vue-router'
  import { useUserStore } from '@/stores/userStore'

  const classes = ref([])
  const route = useRoute()
  const courseId = route.params.id
  const hasJoined = ref(false)
  const teacherNamesMap = ref({})
  const studentCountMap = ref({})
  const courseNameMap = ref({})

  const userStore = useUserStore()
  const userId = userStore.user?.userId || ''
  onMounted(async () => {
    try {
      // 第一步：获取课程下所有班级
      const res = await axios.get(`/api/classes/course/${courseId}`)
      classes.value = res.data

      // 第二步：为每个班级请求额外信息
      for (const cls of classes.value) {
        const classId = cls.classesId

        // 教师信息
        try {
          const tRes = await axios.get(`/api/classes/${classId}/teachers/ids`)
          // 获取教师ID列表后，需要获取教师详细信息
          const teacherIds = tRes.data
          const teacherNames = []
          for (const teacherId of teacherIds) {
            try {
              const userRes = await axios.get(`/api/users/${teacherId}`)
              teacherNames.push(userRes.data.userName)
            } catch (err) {
              console.error(`获取教师信息失败: ${teacherId}`, err)
            }
          }
          teacherNamesMap.value[classId] = teacherNames.join('，')
        } catch (err) {
          console.error(`获取教师失败: ${classId}`, err)
          teacherNamesMap.value[classId] = '未知教师'
        }

        // 学生数量
        try {
          const sRes = await axios.get(`/api/classes/${classId}/students/ids`)
          studentCountMap.value[classId] = sRes.data.length
        } catch (err) {
          console.error(`获取学生失败: ${classId}`, err)
          studentCountMap.value[classId] = 0
        }

        // 课程名（如果classes中未自带 course.name）
        if (!cls.course?.courseName) {
          try {
            const cRes = await axios.get(`/api/courses/${cls.courseId}`)
            courseNameMap.value[classId] = cRes.data.courseName
          } catch (err) {
            console.error(`获取课程失败: ${classId}`, err)
            courseNameMap.value[classId] = '未知课程'
          }
        }
      }

      // 第三步：检查是否已加入班级
      const checkRes = await axios.get(`/api/classes/course/${courseId}/students/${userId}/joined`)
      hasJoined.value = checkRes.data
    } catch (err) {
      console.error('初始化失败：', err)
    }
  })

  async function joinClass(classId) {
    if (!userId) {
      alert('未登录，无法加入班级')
      return
    }

    try {
      await axios.post(`/api/classes/${classId}/students/${userId}`)
      alert('成功加入班级！')
      hasJoined.value = true
      try {
        const sRes = await axios.get(`/api/classes/${classId}/students`)
        studentCountMap.value[classId] = sRes.data.length
      } catch (err) {
        console.error(`刷新学生人数失败: ${classId}`, err)
      }
    } catch (err) {
      alert('加入失败：' + (err.response?.data || err.message))
    }
  }

  async function checkJoined() {
    try {
      const res = await axios.get(`/api/classes/course/${courseId}/students/${userId}/joined`)
      hasJoined.value = res.data
    } catch (err) {
      console.error('检查是否加入失败', err)
    }
  }

  onMounted(() => {
    checkJoined()
  })
</script>

<style scoped>
  .my-container {
    max-width: 100vw;       /* 或 720px，按你卡片宽度调整 */
    /* width: 100%;     */
    margin: 0 auto;
    padding: 0 18px;
  }

  .mb-4 {
    text-align: left;
  }

  .modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.4);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
  }

  .modal-box {
    background: white;
    padding: 20px;
    border-radius: 6px;
    width: 400px;
    max-width: 90%;
  }
  .class-list-card {
  border-radius: 1.2rem !important;
  box-shadow: 0 4px 24px 0 rgba(33, 37, 41, 0.10) !important;
  overflow: hidden;
}
.card-header.bg-primary {
  background: #007bff !important;
  border-radius: 1.2rem 1.2rem 0 0 !important; /* 顶部圆角 */
}
.list-group {
  border-radius: 0 0 1.2rem 1.2rem !important; /* 底部圆角 */
  overflow: hidden;
}
.list-group-item {
  font-size: 1.06rem;
  color: #222 !important;
  border: none;
  border-radius: 0 !important;
  padding-top: 1.1rem;
  padding-bottom: 1.1rem;
}
.list-group-item:last-child {
  border-bottom: none !important;
}

</style>
